package com.helwen.utils;


import com.helwen.entity.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * servlet web容器下相关通用方法
 * @author xay
 * @version 1.0
 * @since 2020/11/2
 */
@Slf4j
public abstract class ServletUtils {

    private ServletUtils(){}

    /**
     * 获取当前用户登陆信息
     * */
    public static UserDto currentUser(){
        // return Optional.ofNullable(CurrentUserUtil.getCurrentUser(getRequest())).orElseThrow(() -> new RuntimeException("当前登陆用户信息为空"));
        return new UserDto();
    }


    /**
     * 获取当前用户Id
     * */
    public static Long currentUserId(){
        // return Optional.ofNullable(CurrentUserUtil.getCurrentUser(getRequest())).map(UserDto::getId).orElseThrow(() -> new RuntimeException("当前登陆用户信息为空"));
        return 0l;
    }

    /**
     * 获取当前用户手机号
     * */
    public static String currentUserMobile(){
        //return Optional.ofNullable(CurrentUserUtil.getCurrentUser(getRequest())).map(UserDto::getUsername).orElseThrow(() -> new RuntimeException("当前登陆用户信息为空"));
        return null;
    }

    /**
     * 安全获取当前用户登陆信息
     * */
    public static Optional<UserDto> safeCurrentUser(){
        HttpServletRequest request = null;
        try {
            request = getRequest();
        }catch (RuntimeException e){
            log.debug("[系统日志][safeCurrentUser]当前线程不存在web上下文环境中");
        }
        UserDto currentUser = new UserDto();
        /*if(null != request){
            currentUser = CurrentUserUtil.getCurrentUser(request);
        }*/
        return Optional.ofNullable(currentUser);
    }


    /**
     * 获取当前用户城市信息
     * */
    public static String currentUserCity(){
        return Optional.ofNullable(currentUser().getTenantId()).orElseThrow(() -> new RuntimeException("当前登陆用户信息异常"));
    }


    public static HttpServletRequest getRequest(){
        return  ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
    }

    public static HttpServletResponse getResponse(){
        return  ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getResponse();
    }

}
